﻿using System;
using System.Xml.Serialization;

namespace UTable.Core.Configuration
{
    /// <summary>
    /// The whole information of a type of class, used for Create Instance.
    /// </summary>
    [Serializable]
    public class ClassConfiguration
    {
        #region Properties

        /// <summary>
        /// Class Type
        /// e.g. UTable.Core.Input.MultiMouseProvider
        /// </summary>
        [XmlAttribute]
        public string TypeString { get; set; }

        /// <summary>
        /// The Assembly the class belongs to.
        /// e.g. UTable.Core
        /// </summary>
        [XmlAttribute]
        public string Assembly { get; set; }

        /// <summary>
        /// Class Version
        /// 1.0.0.0
        /// </summary>
        [XmlAttribute]
        public string Version { get; set; }

        /// <summary>
        /// Supported Culture
        /// neutral
        /// </summary>
        [XmlAttribute]
        public string Culture { get; set; }

        /// <summary>
        /// "null"
        /// </summary>
        [XmlAttribute]
        public string PublicKeyToken { get; set; }

        [XmlIgnore]
        public string AssemblyNameString
        {
            get
            {
                return TypeString + ", " + Assembly + ", Version=" + Version + ", Culture=" + Culture + ", PublicKeyToken=" + PublicKeyToken;
            }
        }

        /// <summary>
        /// Type from TypeString
        /// </summary>
        [XmlIgnore]
        public Type Type { get; set; }
        
        #endregion

        #region Initialization

        /// <summary>
        /// Constructor without parameter for serialization
        /// </summary>
        public ClassConfiguration()
        {
            Version = "1.0.0.0";
            Culture = "neutral";
            PublicKeyToken = "null";
        }

        public void SetType()
        {
            Type = null;
            try
            {
                Type = System.Type.GetType(AssemblyNameString);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }

        #endregion

        #region Public Methods

        public object CreateInstance(object[] args)
        {
            object instance = null;
            try
            {
                instance = Activator.CreateInstance(Type, args);
            }
            catch (System.Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            return instance;
        }

        public object CreateInstance()
        {
            return CreateInstance(new object[] { });
        }

        #endregion
    }
}
